#include <iostream>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"
#include "log.hpp"

void usage()
{
    std::cout << "usage:\n\t" << "./tcp_client server_ip server_port\n" << std::endl; 
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage();
        exit(USAGE_ERR);
    }

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        // std::cerr << "create socket error: " << strerror(errno) << std::endl;
        LogMessage(Fatal, "create socket error, error: %d, reason: %s", errno, strerror(errno));
        exit(SOCK_ERR);
    }

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    
    int cnt = 5;
    // 将该文件描述符转换为网络文件，通过 “流式服务” 进行网络通信
    while(connect(sock, (struct sockaddr*)&server, sizeof(server)) != 0)
    {
        std::cout << "正在尝试重新连接, 还有剩余次数：" << cnt-- << std::endl;
        sleep(1);
        if(cnt < 0) break;
    }

    if(cnt < 0)
    {
        // std::cout << "连接失败！" << std::endl;
        LogMessage(Fatal, "connect error, error: %d, reason: %s", errno, strerror(errno));
        exit(CONNECT_ERR);
    }

    while(true)
    {
        std::string message;
        std::cout << "Enter message# ";
        std::getline(std::cin, message);
        // 写入消息
        write(sock, message.c_str(), message.size());
        // 收到消息
        char buffer[1024];
        ssize_t n = read(sock, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "Ret message# " << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "server quit" << std::endl;
            break;
        }
        else
        {
            std::cerr << "read error: " << strerror(errno) << std::endl;
            exit(READ_ERR);
        }
    }

    return 0;
}